package org.gruposp2p.proyectokarma.service

import org.gruposp2p.proyectokarma.domain.Peer;
import org.gruposp2p.proyectokarma.domain.Document;
import org.gruposp2p.proyectokarma.domain.Comment;
import org.gruposp2p.proyectokarma.domain.Vote;
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.codehaus.groovy.grails.web.json.JSONObject
import org.gruposp2p.proyectokarma.util.VoteResult;

class VoteService {
	
	static transactional = true

	def processVote(Peer peer, JSONObject jsonVote) {
		def voteResult
		def vote
		try {
			if (!(jsonVote.isNull("documentId") || "".equals(jsonVote.documentId))
				&& !(jsonVote.isNull("commentId") || "".equals(jsonVote.commentId))) {
				voteResult = new VoteResult(responseStatus:400,
					messageCode:'proyectokarma.vote.documentAndComment')
				return voteResult
			}
			if ((jsonVote.isNull("documentId") || "".equals(jsonVote.documentId))
				&& (jsonVote.isNull("commentId") || "".equals(jsonVote.commentId))) {
				voteResult = new VoteResult(responseStatus:400,
					messageCode:'proyectokarma.vote.withoutDocumentOrComment')
				return voteResult
			}
			if (jsonVote.documentId) {
				def document = Document.get(jsonVote.documentId)
				if (!document) {
					voteResult = new VoteResult(responseStatus:404,
						messageCode:'proyectokarma.vote.documentNotFound')
					return voteResult
				}
				def alreadyVote = Vote.findWhere(document:document, peerFrom:peer)
				if (alreadyVote) {
					voteResult = new VoteResult(responseStatus:400,
						messageCode:'proyectokarma.vote.documentAlreadyVoted', vote: alreadyVote)
					return voteResult
				}
				vote = new Vote (document: document, peerFrom:peer,
					stringValue:jsonVote.stringValue, numericValue:jsonVote.numericValue)
				vote.save()
			} else if (jsonVote.commentId) {
				def comment = Comment.get(jsonVote.commentId)
				if (!comment) {
					voteResult = new VoteResult(responseStatus:404,
						messageCode:'proyectokarma.vote.commentNotFound')
					return voteResult
				}
				def alreadyVote = Vote.findWhere(comment:comment, peerFrom:peer)
				if (alreadyVote) {
					voteResult = new VoteResult(responseStatus:400,
						messageCode:'proyectokarma.vote.commentAlreadyVoted', vote: alreadyVote)
					return voteResult
				}
				vote = new Vote (comment: comment, peerFrom:peer,
					stringValue:jsonVote.stringValue)
				vote.save()
			}
			voteResult = new VoteResult(responseStatus:201, vote:vote)
			return voteResult
		} catch (Exception ex) {
			log.error "Error: ${ex.message}", ex
			voteResult = new VoteResult(responseStatus:400,
				messageCode:'proyectokarma.vote.systemError')
			return voteResult
		}
		
	}

	
}

